package api;

import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import Dao.UserDao;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.Common;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        User user = Common.checkLoginStatus(req);
        // 没登录的情况
        if(user == null){
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("<script>alert('当前用户未登录')</script>");
            return;
        }

        String blogId = req.getParameter("blogId");
        if(blogId == null){
            // 这里是主页界面
            String jsonString = objectMapper.writeValueAsString(user);
            resp.getWriter().write(jsonString);
        }else{
            // 这是详情页界面
            BlogDao blogDao = new BlogDao();
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            if (blog == null){
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write("<script>alert('当前用户未登录')</script>");
                return;
            }
            UserDao userDao = new UserDao();
            User author = userDao.selectById(blog.getUserId());
            String jsonString = objectMapper.writeValueAsString(author);
            resp.getWriter().write(jsonString);
        }

    }
}
